<!--
 * Copyright © 2023
 * @Author: zhangxiang
 * @Date: 2023-09-20 14:57:20
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-09-20 17:08:31
 * @Description:
 *
-->

<template>
  <el-dialog
    class="agency-cost-setting-dialog"
    :title="'设置代理价格'"
    :visible="show"
    width="500px"
    top="15vh"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="closeClick"
  >
    <div class="center">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="折扣系数" name="discount" />
        <el-tab-pane label="模板导入" name="template" />
      </el-tabs>
      <el-row v-if="activeTab === 'discount'" type="flex" align="middle">
        <div class="subtitle">折扣系数</div>
        <el-input-number
          v-model="discount"
          size="small"
          :step="0.1"
          :min="0"
          :max="1"
          placeholder="请输入折扣系数"
        />
      </el-row>
      <el-row v-if="activeTab === 'template'">
        <file-uploader
          :file.sync="templateFile"
          :name.sync="templateFileName"
          :btn-text="'选择文件'"
          :accept="'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel'"
        />
        <el-button
          type="success"
          plain
          style="margin-top: 10px"
          :loading="downloadLoading"
          @click="downloadTemplateClick"
        >下载模板</el-button>
      </el-row>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancelClick">取 消</el-button>
      <el-button
        type="primary"
        size="small"
        :loading="confirmLoading"
        @click="confirmClick"
      >确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import FileUploader from '@/components/FileUploader'
import {
  saveAgencyCostDiscount,
  saveAgencyCostTemplate,
  getFlavorCostTemplate
} from '@/api/cnap/scheduling-engine'

export default {
  name: 'AgencyCostSettingDialog',
  components: {
    FileUploader
  },
  props: {
    // 是否显示
    show: {
      type: Boolean,
      default: false
    },
    // 云商账户信息
    cloudInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      activeTab: 'discount',
      discount: 0,
      templateFile: null,
      templateFileName: '',
      downloadLoading: false,
      confirmLoading: false
    }
  },
  computed: {},
  watch: {},
  mounted() {},
  methods: {
    /**
     * @description: 下载模板
     * @return {*}
     */
    downloadTemplateClick() {
      this.downloadLoading = true
      getFlavorCostTemplate({
        cloudType: this.cloudInfo.cloudName,
        accountName: this.cloudInfo.accountName
      })
        .then((response) => {
          const fileNames =
            response.headers['content-disposition'].split('fileName=') // 读取文件名
          const fileName =
            fileNames.length > 1
              ? decodeURIComponent(fileNames[1])
              : '云商规格-成本模板.xls' // 解析文件名
          const blob = new Blob([response.data], {
            type: 'application/vnd.ms-excel'
          }) // 新建blob
          const elementA = document.createElement('a') // 创建 element a
          elementA.style.display = 'none' // 设置不可见
          elementA.href = window.URL.createObjectURL(blob) // 设置href
          elementA.download = fileName // 设置名称
          document.body.appendChild(elementA) // 添加到body
          elementA.click() // 模拟点击
          window.URL.revokeObjectURL(elementA.href) // 释放内存
        })
        .catch((err) => {
          console.log(err)
          this.$message.error('下载失败，请稍候再试') // 导出失败
        })
        .finally(() => {
          this.downloadLoading = false // 取消loading
        })
    },
    /**
     * @description: 确定
     * @return {*}
     */
    confirmClick() {
      if (this.activeTab === 'discount') {
        if (Number(this.discount) <= 0 || Number(this.discount) > 1) {
          this.$message.warning('折扣系数需大于0')
          return
        }
        this.confirmLoading = true
        saveAgencyCostDiscount({
          cloudType: this.cloudInfo.cloudName,
          accountName: this.cloudInfo.accountName,
          priceOff: this.discount
        })
          .then((res) => {
            this.closeClick()
            this.$emit('success')
          })
          .finally(() => {
            this.confirmLoading = false
          })
      } else {
        if (!this.templateFile) {
          this.$message.warning('请选择需上传的模板文件')
          return
        }
        this.confirmLoading = true
        const params = new FormData()
        params.append('cloudType', this.cloudInfo.cloudName)
        params.append('accountName', this.cloudInfo.accountName)
        params.append('costTemplateFile ', this.templateFile)
        saveAgencyCostTemplate(params)
          .then((res) => {
            this.closeClick()
            this.$emit('success')
          })
          .finally(() => {
            this.confirmLoading = false
          })
      }
    },
    /**
     * @description: 关闭
     * @return {*}
     */
    closeClick() {
      this.$emit('update:show', false)
    },
    /**
     * @description: 取消
     * @return {*}
     */
    cancelClick() {
      this.closeClick()
      this.$emit('cancel')
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.agency-cost-setting-dialog {
  .subtitle {
    margin-right: 10px;
    .textStyle(14px, 400, #4a4a4a);
    line-height: 20px;
  }
}
</style>
